package repository

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Slice"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/periodTask"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
)

type RepoLocalAppCleanTask struct {
}

func (e *RepoLocalAppCleanTask) TaskType() periodTask.TaskType {
	return periodTask.TaskOnce
}

func (e *RepoLocalAppCleanTask) SchedulePeriod() int64 {
	return 1
}

func (e *RepoLocalAppCleanTask) Execute() {
	// 扫码本地conf信息
	serviceConfList := make([]map[string]interface{}, 0)
	serviceConfList = Slice.Append(serviceConfList, LocalAppConf.readConfFileType("kernel"))
	serviceConfList = Slice.Append(serviceConfList, LocalAppConf.readConfFileType("system"))
	serviceConfList = Slice.Append(serviceConfList, LocalAppConf.readConfFileType("service"))

	// 构造本地信息key
	localMap := make(map[string]*edgeEntity.RepoCompEntity)
	for _, serviceConf := range serviceConfList {
		entity, _ := LocalApplication.buildRepoCompEntityByConf(serviceConf)
		if entity != nil {
			localMap[entity.MakeServiceKey()] = entity
		}
	}

	// 取出app-service组件信息
	existList := commEntityManager.FindEntityList(edgeEntity.Type.RepoCompEntity.Type(), func(value commEntity.IEntity) bool {
		compEntity := value.(*edgeEntity.RepoCompEntity)

		if compEntity.CompRepo != "local" {
			return false
		}
		if compEntity.CompType != "app-service" {
			return false
		}

		return true
	})

	// 删除多余的空组件
	for _, exist := range existList {
		_, ok := localMap[exist.MakeServiceKey()]
		if ok {
			continue
		}

		commEntityManager.DeleteEntity(exist)
	}
}
